/**
 * API 工具类
 * 用于调用后端接口
 */

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api';

// 请求拦截器
const request = async (url: string, options: RequestInit = {}) => {
  const token = localStorage.getItem('admin_token');
  
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    ...options.headers,
  };

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}${url}`, {
    ...options,
    headers,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: '请求失败' }));
    throw new Error(error.detail || `HTTP error! status: ${response.status}`);
  }

  return response.json();
};

// GET 请求
export const get = (url: string) => request(url, { method: 'GET' });

// POST 请求
export const post = (url: string, data?: any) =>
  request(url, {
    method: 'POST',
    body: JSON.stringify(data),
  });

// PUT 请求
export const put = (url: string, data?: any) =>
  request(url, {
    method: 'PUT',
    body: JSON.stringify(data),
  });

// DELETE 请求
export const del = (url: string) => request(url, { method: 'DELETE' });

// 文件上传请求
export const uploadFile = async (url: string, file: File): Promise<any> => {
  const token = localStorage.getItem('admin_token');
  const formData = new FormData();
  formData.append('file', file);

  const headers: HeadersInit = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}${url}`, {
    method: 'POST',
    headers,
    body: formData,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: '上传失败' }));
    throw new Error(error.detail || `HTTP error! status: ${response.status}`);
  }

  return response.json();
};

// 多文件上传请求
export const uploadMultipleFiles = async (url: string, files: File[]): Promise<any> => {
  const token = localStorage.getItem('admin_token');
  const formData = new FormData();
  files.forEach((file) => {
    formData.append('files', file);
  });

  const headers: HeadersInit = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}${url}`, {
    method: 'POST',
    headers,
    body: formData,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: '上传失败' }));
    throw new Error(error.detail || `HTTP error! status: ${response.status}`);
  }

  return response.json();
};

// 作品相关API
export const worksApi = {
  // 获取作品列表
  getWorks: (params?: { skip?: number; limit?: number; is_active?: boolean }) => {
    const query = new URLSearchParams();
    if (params?.skip !== undefined) query.append('skip', params.skip.toString());
    if (params?.limit !== undefined) query.append('limit', params.limit.toString());
    if (params?.is_active !== undefined) query.append('is_active', params.is_active.toString());
    const queryString = query.toString();
    return get(`/works${queryString ? `?${queryString}` : ''}`);
  },

  // 获取作品详情
  getWorkDetail: (id: number) => get(`/works/${id}`),

  // 创建作品
  createWork: (data: {
    title: string;
    subtitle: string;
    cover_image?: string;
    description?: string;
    images?: Array<{ image_url: string; sort_order?: number }>;
  }) => post('/works', data),

  // 更新作品
  updateWork: (id: number, data: {
    title?: string;
    subtitle?: string;
    cover_image?: string;
    description?: string;
    is_active?: boolean;
  }) => put(`/works/${id}`, data),

  // 删除作品（软删除）
  deleteWork: (id: number) => del(`/works/${id}`),
};

// 上传相关API
export const uploadApi = {
  // 上传单个文件
  uploadFile: (file: File) => uploadFile('/upload', file),

  // 上传多个文件
  uploadMultipleFiles: (files: File[]) => uploadMultipleFiles('/upload/multiple', files),
};

// 用户相关API
export const usersApi = {
  // 获取用户列表（通过openid查询，这里简化处理）
  getUsers: (params?: { skip?: number; limit?: number }) => {
    const query = new URLSearchParams();
    if (params?.skip !== undefined) query.append('skip', params.skip.toString());
    if (params?.limit !== undefined) query.append('limit', params.limit.toString());
    const queryString = query.toString();
    // 注意：后端没有用户列表接口，这里需要扩展后端或使用其他方式
    // 暂时返回空数组，实际应该调用后端接口
    return Promise.resolve([]);
  },

  // 获取用户详情
  getUser: (id: number) => get(`/users/${id}`),

  // 通过openid获取用户
  getUserByOpenid: (openid: string) => get(`/users/openid/${openid}`),
};

// 收藏相关API（用于统计等）
export const favoritesApi = {
  // 获取收藏列表
  getFavorites: (userId: number, params?: { skip?: number; limit?: number }) => {
    const query = new URLSearchParams();
    query.append('user_id', userId.toString());
    if (params?.skip !== undefined) query.append('skip', params.skip.toString());
    if (params?.limit !== undefined) query.append('limit', params.limit.toString());
    return get(`/favorites?${query.toString()}`);
  },
};

